package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    //订单超时未支付,每分钟判断一次,超过15分钟将其取消
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void cancelOrder(){
        log.info("取消订单", LocalDateTime.now());
        //查询数据库,根据order_time距离当前时间超过15分钟的订单,将其状态改为已取消
        List<Orders> overOrders = orderMapper.getOverOrderTime(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (overOrders != null && overOrders.size() > 0){
            for (Orders order : overOrders) {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("超时未支付,系统自动取消");
                order.setCancelTime(LocalDateTime.now());
                orderMapper.changeStatus(order);
            }
        }
    }
    //订单自动已完成,每天凌晨一点自动更新一次
    @Scheduled(cron = "0 0 1 * * ? ")
    public void completeOrder(){
        log.info("自动完成订单", LocalDateTime.now());
        //查询数据库,根据order_time距离当前时间超过15分钟的订单,将其状态改为已取消
        List<Orders> overOrders = orderMapper.getOverOrderTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusMinutes(-60));
        if (overOrders != null && overOrders.size() > 0){
            for (Orders order : overOrders) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.changeStatus(order);
            }
        }
    }
}
